package com.globallogic.vkulyk.AnagramsDetector;

import java.util.*;

/**
 * receives input of two strings and gives the output to screen telling whether
 * these words are anagrams. An anagram is a word or a phrase that can be
 * created by rearranging the letters of another given word or phrase. The all
 * letters of "Desperation" can be rearranged to the phrase "A Rope Ends It". We
 * ignore white spaces and letter case.
 * 
 * @author Viacheslav Kulyk
 * @version 1.0 20 Jan 2013
 */

public class AnagramsDetector {

	public static final String ARE_ANAGRAMS = "These are anagrams.";
	public static final String NOT_ANAGRAMS = "These are not anagrams.";
	private String phrase1 = "";
	private String phrase2 = "";
	private boolean areAnagrams = false;

	public static void main(String[] args) {
		new AnagramsDetector().detectAnagrams();
	}

	private void detectAnagrams() {
		getPhrases();
		comparePhrases();
		printResult();
	}

	private void getPhrases() {
		Scanner scanner = new Scanner(System.in);
		System.out
				.print("Enter the first word or phrase and press 'Enter' key:");
		phrase1 = scanner.nextLine().toLowerCase().replaceAll("\\s", "");
		System.out
				.print("Enter the second word or phrase and press 'Enter' key:");
		phrase2 = scanner.nextLine().toLowerCase().replaceAll("\\s", "");
	}

	private void comparePhrases() {
		char[] charsInPhrase1 = phrase1.toCharArray();
		char[] charsInPhrase2 = phrase2.toCharArray();
		areAnagrams = true;
		if (charsInPhrase1.length != charsInPhrase2.length) {
			areAnagrams = false;
		} else {
			for (char aChar : charsInPhrase1) {
				int quantityOfLetterInPhrase1 = 0;
				int quantityOfLetterInPhrase2 = 0;
				for (char charInPhrase1 : charsInPhrase1) {
					if (aChar == charInPhrase1) {
						quantityOfLetterInPhrase1 = quantityOfLetterInPhrase1 + 1;
					}
				}
				for (char charInPhrase2 : charsInPhrase2) {
					if (aChar == charInPhrase2) {
						quantityOfLetterInPhrase2 = quantityOfLetterInPhrase2 + 1;
					}
				}
				if (quantityOfLetterInPhrase1 != quantityOfLetterInPhrase2) {
					areAnagrams = false;
					break;
				}
			}
		}
	}

	private void printResult() {
		if (areAnagrams) {
			System.out.print(AnagramsDetector.ARE_ANAGRAMS);
		} else {
			System.out.print(AnagramsDetector.NOT_ANAGRAMS);
		}
	}

}
